package com.gitee.wsl.markdown.ui

import coil3.ImageLoader
import coil3.PlatformContext
import coil3.memory.MemoryCache
import coil3.request.ImageRequest
import coil3.request.crossfade

interface ImageLoaderProvider {
    fun provideImageLoader(): ImageLoader
}

interface ImagePreloadManager {
    fun preload(url: String)

    fun remove(url: String)
}


internal class DefaultImagePreloadManager(
    private val context: PlatformContext,
    private val imageLoaderProvider: ImageLoaderProvider,
) : ImagePreloadManager {
    override fun preload(url: String) {
        val imageLoader = imageLoaderProvider.provideImageLoader()
        val request =
            ImageRequest
                .Builder(context)
                .data(url)
                .build()
        imageLoader.enqueue(request)
    }

    override fun remove(url: String) {
        val imageLoader = imageLoaderProvider.provideImageLoader()
        imageLoader.memoryCache?.remove(MemoryCache.Key(url))
        imageLoader.diskCache?.remove(url)
    }
}


internal class DefaultImageLoaderProvider(
    private val context: PlatformContext,
    //private val fileSystemManager: FileSystemManager,
) : ImageLoaderProvider {
    private val imageLoader by lazy {
        ImageLoader
            .Builder(context)
            /*.components {
                val decoders = getNativeDecoders()
                for (decoder in decoders) {
                    add(decoder)
                }
            }*/.memoryCache {
                MemoryCache
                    .Builder()
                    .maxSizePercent(context, 0.25)
                    .build()
            }/*.diskCache {
                val path = fileSystemManager.getTempDir()
                DiskCache
                    .Builder()
                    .directory(path)
                    .maxSizePercent(0.02)
                    .build()
            }*/.crossfade(true)
            .build()
    }

    override fun provideImageLoader(): ImageLoader = imageLoader
}
